package com.yoomiito.app.utils.wx

import android.app.Activity
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.net.Uri

import com.umeng.socialize.UMAuthListener
import com.umeng.socialize.UMShareAPI
import com.umeng.socialize.UMShareConfig
import com.umeng.socialize.bean.SHARE_MEDIA
import com.yoomiito.app.Constant
import com.yoomiito.app.base.App
import com.yoomiito.app.utils.YMToast

import java.util.ArrayList

import cn.droidlover.xdroidmvp.cache.SharedPref
import cn.droidlover.xdroidmvp.log.XLog
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram
import com.yoomiito.app.BuildConfig
import com.yoomiito.app.showToast
import com.yoomiito.app.utils.L

object WXUtils {

    private val TAG = "WX_Authorization"

    /**
     * 打开微信
     */
    fun openWX(context: Context) {
        val intent = Intent()
        val cmp = ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI")
        intent.action = Intent.ACTION_MAIN
        intent.addCategory(Intent.CATEGORY_LAUNCHER)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        intent.component = cmp
        context.startActivity(intent)
    }

    /**
     * 分享到微信
     */
    fun shareWX(context: Context, text: String, uri: Array<Uri>) {
        val shareIntent = Intent()
        // 1 Finals 2016-11-2 调用系统分享
        shareIntent.action = Intent.ACTION_SEND_MULTIPLE
        shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)

        // 2 Finals 2016-11-2 添加图片数组
        val imageUris = ArrayList<Uri>()
        for (i in uri.indices) {
            imageUris.add(uri[i])
        }
        shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris)
        shareIntent.type = "image/*"
        shareIntent.putExtra("Kdescription", text)
        // 3 Finals 2016-11-2 指定选择微信。
        val mComponentName = ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI")
        shareIntent.component = mComponentName

        // 4 Finals 2016-11-2 开始分享。
        context.startActivity(shareIntent)
    }

    fun wxAuthorization(context: Context, share_media: SHARE_MEDIA, onAuthorizationListener: OnAuthorizationListener?) {
        val config = UMShareConfig()
        config.isNeedAuthOnGetUserInfo(true)
        UMShareAPI.get(context).setShareConfig(config)
        UMShareAPI.get(context).getPlatformInfo(context as Activity, share_media, object : UMAuthListener {
            override fun onStart(share_media: SHARE_MEDIA) {
                XLog.d(TAG, "onStart " + "授权开始")
            }

            override fun onComplete(share_media: SHARE_MEDIA, i: Int, map: Map<String, String>) {
                XLog.d(TAG, "onComplete 授权完成||i:$i")//sdk是6.4.4的,但是获取值的时候用的是6.2以前的(access_token)才能获取到值,未知原因
                val uid = map["uid"]
                val openid = map["openid"]//微博没有
                val unionid = map["unionid"]//微博没有
                val access_token = map["access_token"]
                val refresh_token = map["refreshToken"]//微信,qq,微博都没有获取到
                val expires_in = map["expires_in"]
                val name = map["name"]
                val gender = map["gender"]
                val iconurl = map["iconurl"]
                XLog.d(TAG, "thread-->:" + Thread.currentThread() + "\n" + "uid-->:" + uid + "\n" + "openid-->:" + openid + "\n" + "unionid-->:" + unionid +
                        "\n" + "access_token-->:" + access_token + "\n" + "refresh_token-->:" + refresh_token + "\n" + "expires_in-->:" + expires_in)
                SharedPref.getInstance(App.getInstance()).putString(Constant.WECHAT_OPEN_ID, openid)
                SharedPref.getInstance(App.getInstance()).putString(Constant.WECHAT_UNID_ID, unionid)
                onAuthorizationListener?.onResult(access_token, refresh_token, openid, unionid)
            }

            override fun onError(share_media: SHARE_MEDIA, i: Int, throwable: Throwable) {
                XLog.d(TAG, "onError 授权失败||i:$i")
                YMToast.showText("授权失败")
            }

            override fun onCancel(share_media: SHARE_MEDIA, i: Int) {
                XLog.d(TAG, "onCancel " + "授权取消")
                YMToast.showText("授权取消")
            }
        })
    }

    interface OnAuthorizationListener {
        fun onResult(access_token: String?, refresh_token: String?, openid: String?, unionid: String?)
    }

    fun isInstallWX(activity: Activity): Boolean = UMShareAPI.get(activity).isInstall(activity, SHARE_MEDIA.WEIXIN)

    @JvmOverloads
    fun openMiniProgram(activity: Context, path: String = "", id: String = "gh_fdaef843ac93") {
        var isInstallWx = true
        if (activity is Activity) {
            isInstallWx = isInstallWX(activity)
        }
        if (isInstallWx) {
            val code = WXShareMultiImageHelper.getWXVersionName(App.getInstance())
            L.i("微信版本号：$code")
            if (code.isNotEmpty()) {
                if (code.elementAt(0) < '7') {
                    "打开失败，请更新微信版本".showToast()
                    return
                }
            }
            val req = WXLaunchMiniProgram.Req()
            req.userName = id // 填小程序原始id（官方实例请填写自己的小程序id）
            if (path.isNotEmpty()) req.path = path //拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。
            req.miniprogramType = if (BuildConfig.DEBUG) WXLaunchMiniProgram.Req.MINIPROGRAM_TYPE_PREVIEW else WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE // 可选打开 正式版
//req.miniprogramType = WXLaunchMiniProgram.Req.MINIPROGRAM_TYPE_TEST;// 可选打开 开发版
//req.miniprogramType = WXLaunchMiniProgram.Req.MINIPROGRAM_TYPE_PREVIEW;// 可选打开 体验版
            App.msgApi.sendReq(req)
        } else {
            "打开失败，请安装微信".showToast()
        }
    }
}
